<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="校区品牌" prop="brand">
              <el-select v-model="query.brand" placeholder="">
                <el-option :key="item.id" :label="item.fullName" :value="item.enCode" v-for="item in brandOptions" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="校区全称">
              <el-input v-model="query.fullName" placeholder="校区全称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="校区简称">
              <el-input v-model="query.shortName" placeholder="校区简称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()" native-type="submit">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">{{ $t('common.reset') }}</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll = true" v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll = false" v-else>收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table :ref="'customTable'" v-loading="listLoading" :data="list" @sort-change="sortChange" @current-change="handleCurrentChange" highlight-current-row>
          <template v-for="(item, index) in columnList">
            <template v-if="item.prop == 'flowState' && custom.hasP(item.prop)">
              <el-table-column :prop="item.prop" :label="item.label" :key="index" :align="item.align" :width="item.width" :show-overflow-tooltip="item.overflow || true" :fixed="item.fixed" :formatter="item.formatter">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.flowState == 1">等待审核</el-tag>
                  <el-tag type="success" v-else-if="scope.row.flowState == 2">审核通过</el-tag>
                  <el-tag type="danger" v-else-if="scope.row.flowState == 3">审核驳回</el-tag>
                  <el-tag type="danger" v-else-if="scope.row.flowState == 4">流程撤回</el-tag>
                  <el-tag type="warning" v-else-if="scope.row.flowState == 5">审核终止</el-tag>
                  <el-tag type="info" v-else>等待提交</el-tag>
                </template>
              </el-table-column>
            </template>
            <template v-else-if="item.prop == 'contact' && custom.hasP(item.prop)">
              <el-table-column :prop="item.prop" :label="item.label" :key="index" :align="item.align" :width="item.width" :show-overflow-tooltip="item.overflow || true" :fixed="item.fixed" :formatter="item.formatter">
                <template slot-scope="scope">
                  <span style="color:#ff5b5b;cursor: pointer;" @click="addSubFormHandle(scope.row.id)">合同记录({{ scope.row.consultCount ? scope.row.consultCount : 0 }})</span>
                </template>
              </el-table-column>
            </template>
            <template v-else-if="item.prop == 'channel' && custom.hasP(item.prop)">
              <el-table-column :prop="item.prop" :label="item.label" :key="index" :align="item.align" :width="item.width" :show-overflow-tooltip="item.overflow || true" :fixed="item.fixed" :formatter="item.formatter">
                <template slot-scope="scope">
                  {{ scope.row.channel | dynamicTreeCodeText(channelOptions) }}
                </template>
              </el-table-column>
            </template>
            <template v-else-if="item.prop == 'brand' && custom.hasP(item.prop)">
              <el-table-column :prop="item.prop" :label="item.label" :key="index" :align="item.align" :width="item.width" :show-overflow-tooltip="item.overflow || true" :fixed="item.fixed" :formatter="item.formatter">
                <template slot-scope="scope">
                  {{ scope.row.brand | dynamicCodeText(brandOptions) }}
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column :prop="item.prop" :label="item.label" :key="index" :align="item.align" :width="item.width" :show-overflow-tooltip="item.overflow || true" :fixed="item.fixed" v-if="custom.hasP(item.prop)" :formatter="item.formatter" />
            </template>
          </template>
          <el-table-column label="操作" fixed="right" width="250" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" v-has="'btn_edit'" :disabled="[1, 2, 5].indexOf(scope.row.flowState) > -1" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
              <el-button type="text" size="small" v-has="'btn_remove'" :disabled="[1, 2, 3, 5].indexOf(scope.row.flowState) > -1" @click="handleDel(scope.row.id)" class="cu-table-delBtn">删除</el-button>
              <el-button size="mini" type="text" :disabled="!scope.row.flowState" @click="addOrUpdateHandle(scope.row.id, scope.row.flowState)" v-has="'btn_detail'">详情</el-button>
              <el-button size="mini" type="text" @click="handleSendEmailForRow(scope.row)" v-has="'btn_send_email'" :disabled="scope.row.flowState !== 2">发送邮件</el-button>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <EmailBox v-if="emailVisible" ref="EmailBox" @close="colseEmail" />
    <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <!-- <ContractForm v-if="renewalFormVisible" ref="ContractForm" @close="colseEmail" /> -->
    <name-form v-if="nameFormVisible" ref="NameForm" @refresh="search" />
  </div>
</template>
<script>
import { getTransitionList, delTransition, sendTransitionEmail } from '@/api/crm/transition'
import FlowBox from '@/views/workFlow/components/FlowBox'
import ExportBox from './ExportBox'
import EmailBox from './EmailBox'
// import ContractForm from '../contract/Form'
import NameForm from './NameForm'
export default {
  components: { FlowBox, ExportBox, EmailBox, NameForm },
  name: 'qy',
  data() {
    return {
      showAll: false,
      query: {
        fullName: undefined,
        shortName: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      },
      flowVisible: false,
      exportBoxVisible: false,
      nameFormVisible: false,
      emailVisible: false,
      renewalFormVisible: false,
      columnList: [{ prop: 'customerName', label: '客户信息', width: '140px' }, { prop: 'brand', label: '校区品牌' }, { prop: 'channel', label: '成交渠道', width: '80px' }, { prop: 'consultTime', label: '咨询时间', formatter: this.custom.tableDateFormat }, { prop: 'manageId', label: '招商经理' }, { prop: 'contractNo', label: '合同编号' }, { prop: 'signingDate', label: '签约日期', formatter: this.custom.tableDateFormat, width: '120px' }, { prop: 'fullName', label: '校区全称', width: '300px' }, { prop: 'shortName', label: '校区简称', width: '200px' }, { prop: 'siteArea', label: '场地面积' }, { prop: 'rent', label: '场地月租金', width: '80px' }, { prop: 'area', label: '校区地址', width: '300px' }, { prop: 'schoolName', label: '关联学校关联', width: '150px' }, { prop: 'schoolSituation', label: '学校规模' }, { prop: 'policy', label: '加盟政策', width: '200px' }, { prop: 'siteConditions', label: '场地情况', width: '300px' }, { prop: 'personnel', label: '人员情况', width: '300px' }, { prop: 'designerId', label: '设计师', width: '150px' }, { prop: 'flowState', label: '状态' }],
      schoolIdOptions: [],
      customerIdOptions: [],
      brandOptions: [],
      channelOptions: [],
      brandOptions: [],
      currentRow: undefined
    }
  },
  computed: {},
  created() {
    this.initData()
    this.getChannelOptions()
    this.getBrandOptions()
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  methods: {
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },
    getBrandOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
        this.brandOptions = res
      })
    },
    getChannelOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'ConsultChannels' }).then(res => {
        this.channelOptions = res
      })
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      getTransitionList(query).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          delTransition(id).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    handleCurrentChange(val) {
      this.currentRow = val
    },
    addOrUpdateHandle(id, flowState) {
      let data = {
        id: id || '',
        enCode: '#visualDevTransition',
        flowId: '334172229149394181',
        formType: 1,
        opType: flowState ? 0 : '-1',
        status: flowState
      }
      this.flowVisible = true
      this.$nextTick(() => {
        this.$refs.FlowBox.init(data)
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      }
      this.initData()
    },
    colseFlow(isrRefresh) {
      this.flowVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      }
      this.initData()
    },
    showEmailHandle(row) {
      this.emailVisible = true
      this.$nextTick(() => {
        // this.$refs.EmailBox.init(row.emailContent)
      })
    },
    showRenameHandle() {
      this.nameFormVisible = true
      this.$nextTick(() => {
        this.$refs.NameForm.init(this.currentRow)
      })
    },
    colseEmail(isrRefresh) {
      this.emailVisible = false
    },

    // 发送指定行的邮件
    handleSendEmailForRow(row) {
      this.$confirm(`确定要发送 ${row.fullName} 的交接表邮件吗？`, '提示', {
        type: 'warning'
      })
        .then(() => {
          this.emailSending = true
          sendTransitionEmail(row.id)
            .then(res => {
              this.$message({
                type: 'success',
                message: '邮件发送成功！'
              })
            })
            .catch(error => {
              this.$message({
                type: 'error',
                message: '邮件发送失败：' + (error.message || '未知错误')
              })
            })
            .finally(() => {
              this.emailSending = false
            })
        })
        .catch(() => {})
    }
  }
}
</script>
<style lang="scss" scoped>
.current-row {
  background: oldlace;
}
</style>
